﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MediaRecommender.Model;

namespace MediaRecommender.Controller
{
    public static class PearsonClass
    {
        public static Dictionary<User, double> IndexUsers(User mainUser, List<User> users)
        {
            Dictionary<User, double> comparedUsers = new Dictionary<User, double>();
            double k;

            foreach (User user in users)
            {
                if (user.Name != mainUser.Name)
                {
                    k = CompareUserPair(mainUser, user);
                    comparedUsers.Add(user, k);
                }
            }

            return comparedUsers;
        }

        private static double CompareUserPair(User mainUser, User user)
        {
            List<int> mainRating = new List<int>();
            List<int> userRating = new List<int>();
            int x = 0, y = 0, xy = 0, x2 = 0, y2 = 0;

            foreach (Media media in user.MediaList.Keys)
            {
                if (mainUser.MediaList.Keys.Contains(media))
                {
                    mainRating.Add(mainUser.MediaList[media]);
                    userRating.Add(user.MediaList[media]);
                }
            }

            if (mainRating.Count() < 2)
            {
                return 0;
            }

            for (int i = 0; i < mainRating.Count; i++)
            {
                x += mainRating[i];
                y += userRating[i];
                xy += mainRating[i] * userRating[i];
                x2 += (int)Math.Pow(mainRating[i], 2);
                y2 += (int)Math.Pow(userRating[i], 2);
            }

            return Pearson(x, y, xy, x2, y2, mainRating.Count());
        }

        private static double Pearson(int x, int y, int xy, int x2, int y2, int n)
        {
            return ((n * xy) - (x * y)) / Math.Sqrt(((n * x2) - Math.Pow(x, 2)) * ((n * y2) - Math.Pow(y, 2)));
        }
    }
}